package com.lhd_gm.scheduledtasksystem.service.impl;

import com.lhd_gm.scheduledtasksystem.pojo.JobInfo;
import com.lhd_gm.scheduledtasksystem.service.QuartzService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class QuartzServiceImpl implements QuartzService {
    @Autowired
    private Scheduler scheduler;

    public static Job getClass(String className) throws Exception {
        Class<?> classTemp = Class.forName(className);
        return (Job) classTemp.newInstance();
    }

    @Override
    public String addCronJob(JobInfo jobInfo, String jobClassName) {
        try {
            // 当前任务不存在才进行添加
            JobKey jobKey = JobKey.jobKey(jobInfo.getJobName(), jobInfo.getJobGroup());
            if (scheduler.checkExists(jobKey)) {
                return "exist";
            }
            // 构建 Job
            JobDetail job = JobBuilder.newJob(getClass(jobClassName).getClass())
                    .withDescription(jobInfo.getDescription())
                    .withIdentity(jobKey).build();
            // cron表达式定时构造器
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(jobInfo.getCron());
            // 构建 Trigger
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(TriggerKey.triggerKey(jobInfo.getTriggerName(), jobInfo.getTriggerGroup()))
                    //.startAt(DateUtil.parseDate(start))
                    //.endAt(DateUtil.parseDate(end))
                    .withSchedule(cronScheduleBuilder).build();
            // 启动调度器
            scheduler.scheduleJob(job, trigger);
            scheduler.start();
            return "success";
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String addHttpCronJob(JobInfo jobInfo, String jobClassName, String shtJson) {
        try {
            // 当前任务不存在才进行添加
            JobKey jobKey = JobKey.jobKey(jobInfo.getJobName(), jobInfo.getJobGroup());
            if (scheduler.checkExists(jobKey)) {
                return "exist";
            }
            // 构建 Job
            JobDetail job = JobBuilder.newJob(getClass(jobClassName).getClass())
                    .withDescription(jobInfo.getDescription())
                    .withIdentity(jobKey)
                    .usingJobData("httpConfig", shtJson)
                    .build();
            // cron表达式定时构造器
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(jobInfo.getCron());
            // 构建 Trigger
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(TriggerKey.triggerKey(jobInfo.getTriggerName(), jobInfo.getTriggerGroup()))
                    //.startAt(DateUtil.parseDate(start))
                    //.endAt(DateUtil.parseDate(end))
                    .withSchedule(cronScheduleBuilder).build();
            // 启动调度器
            scheduler.scheduleJob(job, trigger);
            scheduler.start();
            return "success";
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String addShellCronJob(JobInfo jobInfo, String jobClassName, String stJson, String shellPath) {
        try {
            // 当前任务不存在才进行添加
            JobKey jobKey = JobKey.jobKey(jobInfo.getJobName(), jobInfo.getJobGroup());
            if (scheduler.checkExists(jobKey)) {
                return "exist";
            }
            // 构建 Job
            JobDetail job = JobBuilder.newJob(getClass(jobClassName).getClass())
                    .withDescription(jobInfo.getDescription())
                    .withIdentity(jobKey)
                    .usingJobData("shellConfig", stJson)
                    .usingJobData("shellPath", shellPath)
                    .build();
            // cron表达式定时构造器
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(jobInfo.getCron());
            // 构建 Trigger
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(TriggerKey.triggerKey(jobInfo.getTriggerName(), jobInfo.getTriggerGroup()))
                    //.startAt(DateUtil.parseDate(start))
                    //.endAt(DateUtil.parseDate(end))
                    .withSchedule(cronScheduleBuilder).build();
            // 启动调度器
            scheduler.scheduleJob(job, trigger);
            scheduler.start();
            return "success";
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String modifyJob(JobInfo jobInfo) {
        try {
            String triggerName = jobInfo.getTriggerName();
            // 1. 获取触发器的 Key
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName,jobInfo.getTriggerGroup());
            // 2. 获取旧的触发器
            Trigger oldTrigger = scheduler.getTrigger(triggerKey);
            if (oldTrigger == null) {
                return "inexistence";
            }
            // 3. 创建新触发器（保留原有配置）
            CronTrigger newTrigger = TriggerBuilder.newTrigger()
                    .withIdentity(triggerKey)
                    .withSchedule(CronScheduleBuilder.cronSchedule(jobInfo.getCron()))
                    .build();
            // 4. 重新调度任务
            scheduler.rescheduleJob(triggerKey, newTrigger);
            return "success";
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String deleteCronJob(JobInfo jobInfo) {
        try {
            JobKey jobKey = JobKey.jobKey(jobInfo.getJobName(), jobInfo.getJobGroup());
            TriggerKey triggerKey = TriggerKey.triggerKey(jobInfo.getTriggerName(), jobInfo.getTriggerGroup());
            Trigger trigger = scheduler.getTrigger(triggerKey);
            if (null == trigger) {
                return "removed";
            }
            // 暂停触发器
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器
            scheduler.unscheduleJob(triggerKey);
            // 删除任务
            scheduler.deleteJob(jobKey);
            return "success";
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String executeImmediately(JobInfo jobInfo, String jobClassName) {
        try {
            JobKey jobKey = JobKey.jobKey(jobInfo.getJobName(), jobInfo.getJobGroup());
            JobDetail job = JobBuilder.newJob(getClass(jobClassName).getClass())
                    .withIdentity(jobKey).build();
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(TriggerKey.triggerKey(jobInfo.getTriggerName(), jobInfo.getTriggerGroup()))
                    .build();
            // 启动调度器
            scheduler.scheduleJob(job, trigger);
            scheduler.start();
            return "success";
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int pauseJob(String jobName, String jobGroup) {
        JobKey jobKey = JobKey.jobKey(jobName,jobGroup);
        try {
            if (scheduler.checkExists(jobKey)){
                scheduler.pauseJob(jobKey);
                return 1;
            }else {
                return 0;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int pauseTrigger(String triggerName, String triggerGroup) {
        TriggerKey triggerKey = TriggerKey.triggerKey(triggerName,triggerGroup);
        try {
            if (scheduler.checkExists(triggerKey)){
                scheduler.pauseTrigger(triggerKey);
                return 1;
            }else {
                return 0;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int resumeJob(String jobName, String jobGroup) {
        JobKey jobKey = JobKey.jobKey(jobName,jobGroup);
        try {
            if (scheduler.checkExists(jobKey)){
                scheduler.resumeJob(jobKey);
                return 1;
            }else {
                return 0;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int resumeTrigger(String triggerName, String triggerGroup) {
        TriggerKey triggerKey = TriggerKey.triggerKey(triggerName,triggerGroup);
        try {
            if (scheduler.checkExists(triggerKey)){
                scheduler.resumeTrigger(triggerKey);
                return 1;
            }else {
                return 0;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Trigger.TriggerState getTriggerState(String triggerName, String triggerGroup) {
        TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroup);
        try {
            return scheduler.getTriggerState(triggerKey);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
